<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户注册系统</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <link rel="stylesheet" href="css/register.css">
</head>

<body>
  <div id="app">
    <div class="container">
      <div class="left-panel">
        <h1>加入我们的平台</h1>
        <p>注册账号，解锁所有功能，开启您的教学/学习之旅</p>

        <div class="features">
          <div class="feature">
            <i class="fas fa-shield-alt"></i>
            <div>
              <h3>安全可靠</h3>
              <p>端到端加密保护您的个人信息</p>
            </div>
          </div>
          <div class="feature">
            <i class="fas fa-rocket"></i>
            <div>
              <h3>高效便捷</h3>
              <p>快速注册流程，立即开始使用</p>
            </div>
          </div>
          <div class="feature">
            <i class="fas fa-users"></i>
            <div>
              <h3>社区支持</h3>
              <p>加入活跃的教育社区，共享资源</p>
            </div>
          </div>
        </div>
      </div>

      <div class="register-form">
        <div class="form-header">
          <h2>创建账号</h2>
          <p>请填写以下信息完成注册</p>
        </div>

        <form @submit.prevent="handleSubmit">
          <div class="form-group">
            <label for="name">姓名</label>
            <input type="text" id="name" v-model="formData.name" placeholder="请输入您的全名" required>
            <div class="error-message" :class="{ 'show': errors.name }">请输入有效的姓名</div>
          </div>

          <div class="form-group">
            <label for="userId">学生号/员工号</label>
            <input type="text" id="userId" v-model="formData.userId" placeholder="请输入您的学号或工号" required>
            <div class="error-message" :class="{ 'show': errors.userId }">请输入有效的ID</div>
          </div>

          <div class="form-group">
            <label for="email">电子邮箱</label>
            <input type="email" id="email" v-model="formData.email" placeholder="example@domain.com" required>
            <div class="error-message" :class="{ 'show': errors.email }">请输入有效的电子邮箱</div>
          </div>

          <div class="form-group">
            <label for="password">密码</label>
            <div class="password-container">
              <input :type="showPassword ? 'text' : 'password'" id="password" v-model="formData.password"
                placeholder="设置您的密码" required @input="checkPasswordStrength">
              <span class="toggle-password" @click="showPassword = !showPassword">
                <i :class="showPassword ? 'far fa-eye-slash' : 'far fa-eye'"></i>
              </span>
            </div>
            <div class="password-strength">
              <div class="password-strength-meter"
                :style="{ width: passwordStrength + '%', background: passwordStrengthColor }"></div>
            </div>
            <div class="password-rules">
              密码需包含8个以上字符，包括字母和数字
            </div>
            <div class="error-message" :class="{ 'show': errors.password }">密码强度不足</div>
          </div>

          <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input type="password" id="confirmPassword" v-model="formData.confirmPassword" placeholder="请再次输入密码"
              required>
            <div class="error-message" :class="{ 'show': errors.confirmPassword }">两次输入的密码不一致</div>
          </div>

          <div class="role-selection">
            <h3>选择您的角色</h3>
            <div class="role-cards">
              <div class="role-card" :class="{ 'selected': formData.role === 'admin' }"
                @click="formData.role = 'admin'">
                <i class="fas fa-crown"></i>
                <h4>管理员</h4>
                <p>系统管理权限</p>
              </div>

              <div class="role-card" :class="{ 'selected': formData.role === 'teacher' }"
                @click="formData.role = 'teacher'">
                <i class="fas fa-chalkboard-teacher"></i>
                <h4>教师</h4>
                <p>教学和课程管理</p>
              </div>

              <div class="role-card" :class="{ 'selected': formData.role === 'student' }"
                @click="formData.role = 'student'">
                <i class="fas fa-user-graduate"></i>
                <h4>学生</h4>
                <p>学习课程和参与活动</p>
              </div>
            </div>
            <div class="error-message" :class="{ 'show': errors.role }">请选择您的角色</div>
          </div>

          <button type="submit" class="submit-btn">注册账号</button>

          <div class="success-message" :class="{ 'show': registrationSuccess }">
            <i class="fas fa-check-circle"></i> 注册成功！即将跳转到登录界面...
          </div>
        </form>

        <div class="login-link">
          已有账号？<a href="#">立即登录</a>
        </div>
      </div>
    </div>
  </div>

  <script>
    const { createApp, ref, reactive, computed } = Vue

    createApp({
      setup() {
        const formData = reactive({
          name: '',
          userId: '',
          email: '',
          password: '',
          confirmPassword: '',
          role: ''
        })

        const errors = reactive({
          name: false,
          userId: false,
          email: false,
          password: false,
          confirmPassword: false,
          role: false
        })

        const showPassword = ref(false)
        const passwordStrength = ref(0)
        const passwordStrengthColor = ref('#e74c3c')
        const registrationSuccess = ref(false)

        const checkPasswordStrength = () => {
          const password = formData.password
          let strength = 0

          // 长度检查
          if (password.length >= 8) strength += 25
          if (password.length >= 12) strength += 15

          // 字符类型检查
          if (/[A-Z]/.test(password)) strength += 15
          if (/[a-z]/.test(password)) strength += 15
          if (/[0-9]/.test(password)) strength += 15
          if (/[^A-Za-z0-9]/.test(password)) strength += 15

          passwordStrength.value = Math.min(strength, 100)

          // 设置颜色
          if (passwordStrength.value < 30) {
            passwordStrengthColor.value = '#e74c3c'
          } else if (passwordStrength.value < 70) {
            passwordStrengthColor.value = '#f39c12'
          } else {
            passwordStrengthColor.value = '#2ecc71'
          }
        }

        const validateForm = () => {
          let isValid = true

          // 重置错误状态
          Object.keys(errors).forEach(key => errors[key] = false)

          // 验证姓名
          if (!formData.name.trim()) {
            errors.name = true
            isValid = false
          }

          // 验证用户ID
          if (!formData.userId.trim()) {
            errors.userId = true
            isValid = false
          }

          // 验证邮箱
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
          if (!emailRegex.test(formData.email)) {
            errors.email = true
            isValid = false
          }

          // 验证密码强度
          if (passwordStrength.value < 50) {
            errors.password = true
            isValid = false
          }

          // 验证确认密码
          if (formData.password !== formData.confirmPassword) {
            errors.confirmPassword = true
            isValid = false
          }

          // 验证角色选择
          if (!formData.role) {
            errors.role = true
            isValid = false
          }

          return isValid
        }

        const handleSubmit = async (e) => {
          if (validateForm()) {
            // 模拟注册请求
            registrationSuccess.value = true

            // 在实际应用中，这里会向后端发送注册请求
            console.log('注册信息:', JSON.stringify(formData, null, 2))

            // 模拟注册请求到Node.js后端
            await registerUser()

            // 重置表单（在实际应用中会在注册成功后进行）
            setTimeout(() => {
              formData.name = ''
              formData.userId = ''
              formData.email = ''
              formData.password = ''
              formData.confirmPassword = ''
              formData.role = ''
              passwordStrength.value = 0
              registrationSuccess.value = false
            }, 3000)
          }
        }

        const registerUser = async () => {
          try {
            const response = await axios.post(
              'http://localhost:3000/register',
              JSON.stringify(formData),
              {
                headers: {
                  'Content-Type': 'application/json'
                }
              }
            );

            // 检查后端返回的 success 字段
            if (response.data.success) {
              console.log('注册成功:', response.data);

              // 这里可以添加成功后的操作
              // - 显示成功消息
              registrationSuccess.value = true; // 更新成功状态
              // - 3秒后跳转到登录页面
              setTimeout(() => {
                window.location.href = 'login.html';
              }, 3000);
              // - 重置表单
              formData.name = '';
              formData.userId = '';
              formData.email = '';
              formData.password = '';
              formData.confirmPassword = '';
              formData.role = '';
              passwordStrength.value = 0;
            } else {
              // 处理后端返回的业务逻辑错误
              console.warn('注册失败:', response.data.message);
              errors.value = response.data.errors || { message: response.data.message };
            }
          } catch (error) {
            // 处理网络或服务器错误
            console.error('请求失败:', error);

            if (error.response) {
              // 服务器返回了错误响应 (4xx/5xx)
              console.error('错误状态码:', error.response.status);
              console.error('错误数据:', error.response.data);

              // 更新错误信息（假设使用 Vue 的 ref）
              errors.value = error.response.data.errors || {
                message: error.response.data.message || '服务器错误'
              };
            } else if (error.request) {
              // 请求已发送但无响应
              errors.value = { message: '无法连接到服务器，请检查网络' };
            } else {
              // 请求配置错误
              errors.value = { message: '请求配置错误: ' + error.message };
            }

            registrationSuccess.value = false; // 确保成功状态为 false
          }
        };

        return {
          formData,
          errors,
          showPassword,
          passwordStrength,
          passwordStrengthColor,
          registrationSuccess,
          checkPasswordStrength,
          handleSubmit
        }
      }
    }).mount('#app')
  </script>
</body>

</html>